package com.app.library.utils

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentUris
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils

class CameraUtils(val activity: Activity) {

    companion object {
        const val TYPE_CAMERA = 1
        const val TYPE_ALBUM = 2
    }

    private var mCameraUrl: Uri? = null
    private var photoUri: Uri? = null

    private var requestCode: Int = 123

    private fun requestPermission(type: Int) {
        val utils = if (type == TYPE_ALBUM) {
            PermissionUtils.permission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        } else {
            PermissionUtils.permission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            )
        }
        utils.callback(object : PermissionUtils.FullCallback {
            override fun onGranted(permissionsGranted: List<String>) {
                LogUtils.d(permissionsGranted)
                if (type == 1) {
                    openCamera()
                } else {
                    selectImage()
                }
            }

            override fun onDenied(
                permissionsDeniedForever: List<String>,
                permissionsDenied: List<String>
            ) {
                LogUtils.d(permissionsDeniedForever, permissionsDenied)

            }
        })
            .request()
    }

    private fun openCamera() {
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        //判断是否有相机
        //if (captureIntent.resolveActivity(packageManager)!= null){ //Android 11 判断为null
        if (activity.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) { //适配Android11
            photoUri = createImageUri()
            mCameraUrl = photoUri
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                activity.startActivityForResult(captureIntent, requestCode)
            }
        }
    }

    @SuppressLint("IntentReset")
    private fun selectImage() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_PICK
        intent.data =
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI //直接打开系统相册  不设置会有选择相册一步（例：系统相册、QQ浏览器相册）
        activity.startActivityForResult(Intent.createChooser(intent, "Select Picture"), requestCode)
    }

    private fun createImageUri(): Uri? {
        val status = Environment.getExternalStorageState()
        //判断是否有SD卡，优先使用SD卡存储，当没有SD卡时使用手机储存
        return if (status.equals(Environment.MEDIA_MOUNTED)) {
            activity.contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                ContentValues()
            )
        } else {
            activity.contentResolver.insert(
                MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                ContentValues()
            )
        }
    }

    fun getImagePath(uri: Uri): String? {
        var path: String? = null
        //根据不同的uri进行不同的解析
        if (DocumentsContract.isDocumentUri(activity, uri)) {
            val docId = DocumentsContract.getDocumentId(uri)
            if ("com.android.providers.media.documents" == uri.authority) {
                val id = docId.split(":").toTypedArray()[1]
                val selection = MediaStore.Images.Media._ID + "=" + id
                path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
            } else if ("com.android.providers.downloads.documents" == uri.authority) {
                val contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"),
                    java.lang.Long.valueOf(docId)
                )
                path = getImagePath(contentUri, null)
            }
        } else if ("content".equals(uri.scheme, ignoreCase = true)) {
            path = getImagePath(uri, null)
        } else if ("file".equals(uri.scheme, ignoreCase = true)) {
            path = uri.path
        }
        //展示图片
        return path
    }

    fun getImagePath(data: Intent): String? {
        val uri = data.data ?: return null
        return getImagePath(uri)
    }

    //content类型的uri获取图片路径的方法
    @SuppressLint("Range")
    private fun getImagePath(uri: Uri?, selection: String?): String? {
        uri ?: return null
        var path: String? = null
        val cursor: Cursor? = activity.contentResolver.query(uri, null, selection, null, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
            }
            cursor.close()
        }
        return path
    }

    fun start(type: Int, requestCode: Int = 111) {
        this.requestCode = requestCode
        requestPermission(type)
    }

    fun getCameraUri(): Uri? {
        return mCameraUrl
    }
}